<template>
  <div class="page">
    <section class="card section">
      <div class="field">
        <label>房间号</label>
        <input class="input" v-model.trim="form.dorm" placeholder="请输入房间号，示例：设备1" />
      </div>

      <button class="primary" @click="query" :disabled="loading">
        {{ loading ? "查询中…" : "查询" }}
      </button>
      
      <template v-if="isShowInfo">
        <div class="result">
          <div class="row">
            <span></span
            ><button class="secondary" @click="goToControl">
              遥控器
            </button>
          </div>
          <div class="row">
            <span>缴费项目</span><span>{{userInfo?.feeProject || "--" }}</span>
          </div>
          <div class="row">
            <span>收费机构</span><span>{{userInfo?.feeCompany || "--" }}</span>
          </div>
          <div class="row">
            <span>所属组织</span>
            <select v-model="paymentItem">
              <option key="userInfo?.organization" v-if="!userInfo?.isPay">{{userInfo?.organization}}</option>
              <option key="制冷费">制冷费</option>
            </select>
          </div>
          <div class="row">
            <span>用户卡号</span><span>{{ userInfo?.cardNumber || "--" }}</span>
          </div>
          <div class="row">
            <span>用户手机号</span><span>{{ userInfo?.phoneNumber || "--" }}</span>
          </div>
          
          <div class="row">
            <span>用户姓名</span><span>{{ userInfo?.name || "--" }}</span>
          </div>
          <div class="row">
            <span>用户地址</span><span>{{ userInfo?.address || "--" }}</span>
          </div>
          <template v-if="paymentItem === userInfo?.organization">
            <div class="row">
              <span>供暖年度</span><span>{{ userInfo?.year || "--" }}</span>
            </div>
            <div class="row">
              <span>应收面积</span><span>{{ userInfo?.area || "--" }}</span>
            </div>
            <div class="row">
              <span>单价</span><span>{{ userInfo?.price || "--" }}</span>
            </div>
            <div class="row">
              <span>计费方式</span><span>{{ userInfo?.feeMethod == 1 ? '按时间段' : userInfo?.feeMethod == 2 ? '按使用时长' : "--" }}</span>
            </div>
            <div class="row">
              <span>收费金额(元)</span><span>{{ userInfo?.fee || "--" }}</span>
            </div>
          </template>
        </div>

        <div class="result">
          <div class="row">
            <span>缴费金额</span>
            <input
              :disabled="paymentItem === userInfo?.organization"
              class="amount-input"
              v-model="form.amount"
              inputmode="decimal"
              placeholder="请输入金额"
              @input="onAmountInput"
            />
          </div>
        </div>
        <button :disabled="!isNowInRange(userInfo?.startTime, userInfo?.endTime) && userInfo?.feeMethod == 1" class="primary" style="background-color: #f75151;" @click="recharge">
          确认充值
        </button>
      </template>
      <p v-if="message" class="msg">{{ message }}</p>
    </section>
  </div>
</template>

<script setup>
import { reactive, ref, computed, watch } from "vue";
import { useRouter } from "vue-router";
import { fetchDeviceInfo } from "../services/api.js";

const router = useRouter();

const form = reactive({ dorm: "", amount: "" });
const isShowInfo = ref(false);
const deviceInfo = ref({});
const userInfo = ref({});
const payRecordList = ref([]);
const paymentItem = ref('制冷费');

const message = ref("");
const loading = ref(false);

const displayDeviceName = computed(
  () => deviceInfo.value?.deviceName || form.dorm
);
watch(paymentItem, (value)=>{
  if(userInfo.value?.organization === value){
    form.amount = userInfo.value?.fee
  }else{
    form.amount = 0
  }
})

 function isNowInRange(start, end) {
  if(!start || !end) return;
  const now = Date.now();               // 当前时间戳（毫秒）

  // 统一转换成毫秒时间戳
  const toTS = (v) => {
    if (typeof v === 'number') return v;              // 已经是时间戳
    if (v instanceof Date)      return v.getTime();   // Date 对象
    if (typeof v === 'string') {
      // HH:mm → 补全当天日期
      if (/^\d{2}:\d{2}$/.test(v)) {
        const today = new Date().toISOString().slice(0, 10); // 今天日期
        v = `${today} ${v}`;
      }
      return new Date(v.replace(' ', 'T')).getTime(); // 兼容大部分浏览器
    }
    throw new TypeError('Unsupported type');
  };

  const startTS = toTS(start);
  const endTS   = toTS(end);

  return now >= startTS && now <= endTS;
}


function normalizeDevice(data, fallbackName) {
  const pattern = data?.pattern || "";
  return {
    ...data,
    deviceName: data?.deviceName ?? fallbackName,
    mac: data?.mac ?? data?.alias ?? "",
    heatingTemperature:
      typeof data?.heatingTemperature === "number"
        ? data.heatingTemperature
        : null,
    cryogenicTemperature:
      typeof data?.cryogenicTemperature === "number"
        ? data.cryogenicTemperature
        : null,
    pattern: pattern,
    windSpeed: data?.windSpeed ?? "",
    deviceStatus: data?.deviceStatus || "pause",
    balance:
      typeof data?.equipmentAmount === "number"
        ? data.equipmentAmount
        : typeof data?.balance === "number"
        ? data.balance
        : 0,
    min: typeof data?.min === "number" ? data.min : 16,
    max: typeof data?.max === "number" ? data.max : 30,
  };
}

async function query() {
  if (!form.dorm) {
    message.value = "请输入房间号";
    return;
  }
  loading.value = true;
  message.value = "";
  deviceInfo.value = {};
  userInfo.value = {};
  isShowInfo.value = false;
  try {
    const data = await fetchDeviceInfo(form.dorm);
    if (data && data.deviceInfo && data.userInfo) {
      isShowInfo.value = true;
      deviceInfo.value = normalizeDevice(data.deviceInfo, form.dorm);
      userInfo.value = data.userInfo;
      payRecordList.value = data.payRecordList;
      if(data.userInfo?.organization && !data.userInfo?.isPay){
        paymentItem.value = data.userInfo?.organization;
      }

      message.value = "";

      if(data.userInfo.feeMethod == 1){
        form.amount = data.userInfo.fee;
      }

    } else {
      message.value = "没有找到该房间";
    }
  } catch (e) {
    message.value = "没有找到该房间";
  } finally {
    loading.value = false;
  }
}

function goToControl() {
  if (!isShowInfo.value) return;
  try {
    sessionStorage.setItem("deviceInfo", JSON.stringify(deviceInfo.value));
  } catch {}
  router.push({
    name: "AcSwitch",
    query: {
      device: displayDeviceName.value,
      dorm: form.dorm,
      mac: deviceInfo.value.mac || "",
    },
  });
}

function onAmountInput(e) {
  const v = e.target.value;
  const cleaned = v
    .replace(/[^\d.]/g, "")
    .replace(/^\./, "")
    .replace(/(\..*)\./g, "$1");
  e.target.value = cleaned;
  form.amount = cleaned;
}

function recharge() {
  if (!isShowInfo.value) return;
  const amount = Number(form.amount);
  if (!form.amount || Number.isNaN(amount)) {
    message.value = "请输入有效金额";
    return;
  }
  form.amount = '';
  console.log(deviceInfo.value);
  console.log(userInfo.value);
  const url = `/pages/recharge/index?payTitle=${paymentItem.value}&amount=${amount}&devicename=${deviceInfo.value.deviceName}&deviceid=${deviceInfo.value.id}`;
  console.log(url);
  // 跳转至小程序支付页面
  wx.miniProgram.navigateTo({
    url,
  });
}

</script>

<style scoped>
.page {
  min-height: 100vh;
  background: var(--bg);
  color: var(--text);
}
.topbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.04);
}
.title {
  font-weight: 600;
  font-size: 16px;
}
.right-actions {
  display: flex;
  gap: 8px;
}
.section {
  padding: 16px;
  margin: 12px;
}
.field {
  display: grid;
  gap: 8px;
  margin-bottom: 12px;
}
label {
  color: #666;
  font-size: 14px;
}
.input,
.amount-input {
  border: none;
  outline: none;
  background: #f8fbff;
  padding: 12px 14px;
  border-radius: 8px;
  box-shadow: inset 0 0 0 1px rgba(31, 85, 255, 0.06);
}
.amount-input {
  text-align: right;
}
.primary {
  width: 100%;
  border: none;
  background: #1f55ff;
  color: #fff;
  padding: 12px;
  border-radius: 10px;
  margin: 8px 0 12px;
  box-shadow: 0 10px 24px rgba(31, 85, 255, 0.18);
}
.primary:disabled{
  background: #ccc !important;
}
.secondary {
  border: 1px solid #1f55ff;
  background: #fff;
  color: #1f55ff;
  padding: 6px 10px;
  border-radius: 10px;
}
.result {
  background: #fff;
  border-radius: 10px;
  padding: 12px;
  box-shadow: 0 8px 20px rgba(31, 85, 255, 0.08);
  margin: 8px 0 12px;
}
.row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 0;
  color: #333;
}
.msg {
  color: #1f55ff;
  font-size: 14px;
}
</style>
